const bcrypt = require('bcryptjs');

const userValidator = async (ctx, next) => {
  const { user_name, password } = ctx.request.body;
  if (!user_name || !password) {
    ctx.app.emit('error', 'userFormateError', ctx);
    return;
  }
  await next();
};

const verifyUser = async (ctx, next) => {
  const { user_name } = ctx.request.body;
  try {
    console.log('ccc');
    const res = await ctx.service.user.getUserInfo({ user_name });
    console.log('ssd', res);
    if (res) {
      console.error('用户名已存在', user_name);
      ctx.app.emit('error', 'userAreadyExisted', ctx);
      return;
    }
  } catch (error) {
    console.error('用户注册错误', error);
    ctx.app.emit('error', 'userRegisterError', ctx);
    return;
  }
  await next();
};

const cryptPassword = async (ctx, next) => {
  const { password } = ctx.request.body;

  const salt = bcrypt.genSaltSync(10);
  const hash = bcrypt.hashSync(password, salt);

  ctx.request.body.password = hash;

  await next();
};

const verifyLogin = async (ctx, next) => {
  const { user_name, password } = ctx.request.body;

  try {
    const res = await ctx.service.user.getUserInfo({ user_name });

    // 1.用户是否存在
    if (!res) {
      console.error('用户不存在', user_name);
      ctx.app.emit('error', 'userDoesNotExist', ctx);
      return;
    }

    console.log(bcrypt.compareSync(password, res.password));
    // 2.密码是否正确
    if (!bcrypt.compareSync(password, res.password)) {
      ctx.app.emit('error', 'invalidPassword', ctx);
      return;
    }
  } catch (error) {
    console.error('用户登录错误', error);
    ctx.app.emit('error', 'userLoginError', ctx);
    return;
  }

  await next();
};
module.exports = { userValidator, verifyUser, verifyLogin, cryptPassword };
